package cinema;

import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;

public class Admin extends User {

    public Admin(String userId, String username, String password, Date registerTime, String userType, String phone) {
        super(userId, username, password, registerTime, userType, phone);
    }

    // 添加用户
    public void addUser(List<User> userList, Scanner scanner) {
        System.out.println("请输入用户ID：");
        String userId = scanner.next();
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入用户类型（经理/前台/管理员）：");
        String userType = scanner.next();
        System.out.println("请输入手机号：");
        String phone = scanner.next();

        // 检查唯一性
        if (isDuplicateUser(userList, userId, username, phone)) {
            System.out.println("用户ID、用户名或手机号已存在，添加失败");
            return;
        }

        // 创建用户对象
        User newUser = createUserByType(userId, username, userType, phone);
        if (newUser == null) {
            System.out.println("用户类型错误");
            return;
        }

        userList.add(newUser);
        System.out.println("用户添加成功");
        Log log = new Log("添加" + userType + ":" + username, this.getUsername());
        log.recordLog();
    }

    // 删除用户
    public boolean deleteUser(List<User> userList, Scanner scanner, String username) {
        if ("admin".equals(username)) {
            System.out.println("不能删除admin账户");
            return false;
        }

        User targetUser = findUser(userList, u -> u.getUsername().equals(username));
        if (targetUser == null) {
            System.out.println("未找到该用户");
            return false;
        }

        System.out.println("确定要删除用户" + username + "吗？（y/n）");
        if (!"y".equalsIgnoreCase(scanner.next())) {
            System.out.println("取消删除");
            return false;
        }

        userList.remove(targetUser);
        System.out.println("删除成功");
        Log log = new Log("删除" + targetUser.getUserType() + ":" + username, this.getUsername());
        log.recordLog();
        return true;
    }

    // 列出所有用户
    public void listAllUsers(List<User> userList) {
        System.out.println("用户ID\t用户名\t注册时间\t用户类型\t手机号");
        userList.forEach(user ->
                System.out.printf("%s\t%s\t%s\t%s\t%s%n",
                        user.getUserId(),
                        user.getUsername(),
                        user.getRegisterTime(),
                        user.getUserType(),
                        user.getPhone()
                )
        );
    }

    // 查询用户
    public void queryUser(List<User> userList, String key, String value) {
        Predicate<User> condition;
        if ("用户ID".equals(key)) {
            condition = u -> u.getUserId().equals(value);
        } else if ("用户名".equals(key)) {
            condition = u -> u.getUsername().equals(value);
        } else {
            System.out.println("无效的查询条件");
            return;
        }

        System.out.println("查询结果：");
        System.out.println("用户ID\t用户名\t注册时间\t用户类型\t手机号");
        userList.stream()
                .filter(condition)
                .forEach(user ->
                        System.out.printf("%s\t%s\t%s\t%s\t%s%n",
                                user.getUserId(),
                                user.getUsername(),
                                user.getRegisterTime(),
                                user.getUserType(),
                                user.getPhone()
                        )
                );
    }

    // 重置密码
    public boolean resetPassword(List<User> userList, String username) {
        User targetUser = findUser(userList, u -> u.getUsername().equals(username));
        if (targetUser == null) {
            System.out.println("未找到该用户");
            return false;
        }

        targetUser.setPassword("123456");
        System.out.println("密码已重置为123456，用户登录时需修改");
        Log log = new Log("重置" + targetUser.getUserType() + ":" + username + "的密码", this.getUsername());
        log.recordLog();
        return true;
    }

    // 修改用户信息
    public void modifyUserInfo(List<User> userList, Scanner scanner, String username) {
        User targetUser = findUser(userList, u ->
                u.getUsername().equals(username) &&
                        ("经理".equals(u.getUserType()) || "前台".equals(u.getUserType()))
        );

        if (targetUser == null) {
            System.out.println("未找到该用户或不允许修改");
            return;
        }

        System.out.println("请选择修改内容：1.用户类型 2.手机号");
        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                System.out.println("请输入新用户类型（经理/前台）：");
                targetUser.setUserType(scanner.next());
                System.out.println("用户类型修改成功");
                break;
            case 2:
                System.out.println("请输入新手机号：");
                targetUser.setPhone(scanner.next());
                System.out.println("手机号修改成功");
                break;
            default:
                System.out.println("无效选择");
        }
    }

    //============ 辅助方法 ============//
    private boolean isDuplicateUser(List<User> users, String userId, String username, String phone) {
        return users.stream().anyMatch(u ->
                u.getUserId().equals(userId) ||
                        u.getUsername().equals(username) ||
                        u.getPhone().equals(phone)
        );
    }

    private User createUserByType(String userId, String username, String userType, String phone) {
        String password = "123456";  // 默认密码
        Date registerTime = new Date();

        switch (userType) {
            case "管理员": return new Admin(userId, username, password, registerTime, userType, phone);
            case "经理": return new Manager(userId, username, password, registerTime, userType, phone);
            case "前台": return new Receptionist(userId, username, password, registerTime, userType, phone);
            default: return null;
        }
    }

    private User findUser(List<User> users, Predicate<User> condition) {
        return users.stream()
                .filter(condition)
                .findFirst()
                .orElse(null);
    }
}